import FlagImage from '@/components/FlagImage';
import * as api from '@/services/vpnGroup';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import Form from './components/Form';

const VpnGroupList: React.FC = () => {
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.VpnGroupModel | undefined>(
    undefined,
  );

  const actionRef = useRef<ActionType>();

  console.log('========= vpngroup list ========');

  const handleFormSubmit = async (record: API.VpnGroupModel) => {
    let result: API.Result;
    if (current) {
      result = await api.update({
        ...current,
        ...record,
      });
    } else {
      result = await api.add({ ...record });
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setFormVisible(false);
      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  let columns: ProColumns<API.VpnGroupModel>[] = [
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 80,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '国家/地区',
      dataIndex: 'flag',
      width: 180,
      render: (text) => (
        <>
          <FlagImage flagName={text as string} />
          {text}
        </>
      ),
    },
    {
      title: '服务器',
      align: 'center',
      dataIndex: 'serverCount',
      width: 80,
    },
    {
      title: '排序',
      align: 'center',
      dataIndex: 'sort',
      width: 80,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => {
        let cmps = [];
        cmps.push(
          <a
            key="edit"
            onClick={(e) => {
              setFormVisible(true);
              setCurrent(record);
            }}
          >
            编辑
          </a>,
        );
        cmps.push(
          <Popconfirm
            key="delete"
            title="确定要删除吗?"
            onConfirm={async () => {
              await handleRemove(record.id);
            }}
          >
            <a>删除</a>
          </Popconfirm>,
        );
        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        search={false}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        pagination={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="create"
            onClick={() => {
              setFormVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={api.list}
      />
      <Form
        visible={formVisible}
        // defaultProductId={undefined}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default VpnGroupList;
